//----------------------微信js-sdk帮助类------------

const JS_APIS = ["updateAppMessageShareData", "updateTimelineShareData",
  "onMenuShareTimeline", "onMenuShareAppMessage", "onMenuShareQQ", //即将废弃
  "onMenuShareWeibo", "onMenuShareQZone", "startRecord", "stopRecord", "onVoiceRecordEnd",
  "playVoice", "pauseVoice", "stopVoice", "onVoicePlayEnd", "uploadVoice", "downloadVoice",
  "chooseImage", "previewImage", "uploadImage", "downloadImage", "translateVoice", "getNetworkType",
  "openLocation", "getLocation", "hideOptionMenu", "showOptionMenu", "hideMenuItems", "showMenuItems",
  "hideAllNonBaseMenuItem", "showAllNonBaseMenuItem", "closeWindow", "scanQRCode", "chooseWXPay", "openProductSpecificView",
  "addCard", "chooseCard", "openCard"
];

const URL_JSSDK_SIGN = "/wx_user/common/js/signature"

define([
  'BaseApi',
  'CacheUtil',
  'jweixin', 'env'
], function (baseApi, cacheUtil, wx) {
  /**
   * 微信js-sdk签名授权
   * @param {*} url 网页路径
   * @param {*} jsApi api数组
   * @param {*} callback 回调
   */
  function wxJsSdkSignature(url, jsApi, callback) {
    url = url.split('#')[0];
    const key = `jssdk:${url}`;
    let success = false;
    let tmp = cacheUtil.get(key);
    if (tmp != null) {
      let data = JSON.parse(tmp);
      wx.config({
        debug: false,
        appId: data.appId,
        timestamp: data.timestamp,
        nonceStr: data.nonceStr,
        signature: data.signature,
        jsApiList: jsApi || JS_APIS
      });
      success = true;
    } else {
      let _url = BASE_URL + URL_JSSDK_SIGN + '?url=' + encodeURIComponent(url);
      baseApi.get(_url, null, {
        onSuccess: function (data) {
          wx.config({
            debug: false,
            appId: data.data.appId,
            timestamp: data.data.timestamp,
            nonceStr: data.data.nonceStr,
            signature: data.data.signature,
            jsApiList: jsApi || JS_APIS
          });
          success = true;
          cacheUtil.set(key, JSON.stringify(data.data), 3600);
        },
        onError: function (errcode, errmsg) {
          console.error("获取微信JSSDK签名失败", errcode, errmsg);
          success = false;
        }
      }, false);
    }
    if (success) {
      // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，
      // 所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
      wx.ready(function () {
        callback(true, wx)
      });
      // config信息验证失败会执行error函数，如签名过期导致验证失败，
      // 具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
      wx.error(function (res) {
        console.error("微信JSSDK签名失败", res)
        callback(false, wx)
      });
    } else {
      callback(false, wx)
    }
  }
  return {
    wxJsSdkSignature: wxJsSdkSignature
  }
});